/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package dao;

import java.util.List;
import javax.persistence.EntityManager;
import Bean.Escola;
import javax.annotation.Resource;
import javax.ejb.SessionContext;
import javax.ejb.Stateless;
import javax.ejb.TransactionAttribute;
import javax.ejb.TransactionAttributeType;
import javax.ejb.TransactionManagement;
import javax.ejb.TransactionManagementType;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;


/**
 *
 * @author alexandre
 */
@Stateless(name = "EscolaDAO")
@TransactionManagement(TransactionManagementType.CONTAINER)
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public class EscolaDAO {
    
    
     @PersistenceContext(unitName = "PersistenceUnit")
    private EntityManager manager;

    @Resource
    private SessionContext context;//Session context que monitora se algum erro ocorre para fazer rollback
    
    public void add(Escola esc){
        try
        {
          manager.persist(esc);   
        }
        catch(Exception e){
            
            e.printStackTrace();
        }
       
    }
    
    
    public void edit(Escola esc){
       
        manager.merge(esc);
    }
    
    
    public void del(Escola esc){
       // EntityManager em = JPAUtil.getInstance().getEntityManager();
        
       Escola esc2 = manager.merge(esc);
        manager.remove(esc2);
    }
    
    public Escola getEscolaID(int id){
        Query query = manager.createQuery("select esc from Escola esc where esc.id=:id");
        query.setParameter("id", id);
        Escola esc = (Escola)query.getSingleResult();
        return esc;
    }
    
    public List<Escola> getListaEscola(){
        List <Escola> toReturn = null;
        Query query = manager.createQuery("select esc From Escola esc");
        toReturn = query.getResultList();
        
        return toReturn;
        
    }
    
    public Escola getEscolaPorInep(String inep){
        Escola esc = manager.find(Escola.class, inep);
        return esc;
        
        
        //return JPAUtil.getInstance().getIstituicaoByInep(Escola.class, "select esc from Escola where esc.inep=:inep", inep);
    }
    
     public  List<Escola> getAlunoByID(int id){
      
           List toReturn = null;
           Query query = manager.createQuery("select aluno From Aluno aluno where id:=" + id + "");
           query.setParameter("id", id);
           toReturn = query.getResultList();
        return toReturn;
        }
}
